//
//  PhotoPictureListViewController.swift
//  SwiftChatUI
//
//  Created by xzk on 2019/2/26.
//  Copyright © 2019年 xzk. All rights reserved.
//

import UIKit

let PhotoPictureListCollectionViewCellId = "PhotoPictureListCollectionViewCellId"

class PhotoPictureListViewController: UIViewController {
    
    public var album: AlbumModel? = nil {
        didSet {
            loadData()
        }
    }
    
    private var dataArray: [PictureModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        
        initView()
        loadData()
    }
    
    private func initView() {
        view.backgroundColor = .white
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.bottom.left.right.equalTo(self.view)
        }
    }
    
    private func loadData() {
        if let album = album {
            PhotoManager.pictures(album) { (images) in
                self.dataArray = images
                self.collectionView.reloadData()
            }
        }
    }
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 5
        layout.minimumLineSpacing = 5
        
        let itemWH: CGFloat = ThumbnailImageWH
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.delegate = self
        view.dataSource = self
        view.register(PhotoPictureListCollectionViewCell.self, forCellWithReuseIdentifier: PhotoPictureListCollectionViewCellId)
        
        return view
    }()
}

extension PhotoPictureListViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoPictureListCollectionViewCellId, for: indexPath) as! PhotoPictureListCollectionViewCell
        
        let model = dataArray[indexPath.row]
        
        cell.backgroundColor = .red
        cell.imageView.image = model.thumbnail()
        
        return cell
    }
}
